<?php

namespace app\command;

use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\PhpWord;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\Validate;

class SoftWord extends Command
{
    protected $pmin = 50;   // 每页最小行数
    protected $pmax = 60;   // 每页最大行数
    protected $page = 80;   // word页数
    protected function configure()
    {
        // 指令配置
        $this->setName('softword')
        ->addArgument('name', Argument::REQUIRED, 'software brand')
        ->addArgument('file', Argument::REQUIRED, 'code file')
        ->setDescription('Generate soft documents');
        // 设置参数
        
    }

    protected function execute(Input $input, Output $output)
    {
        $param = $input->getArguments();
        $validate = Validate::make([
            'name'  => 'require',
            'file'  => function($value){
                return file_exists($value) ?: '文件不存在！';
            }
        ]);
        if( ! $validate->check($param) ){
            echo $validate->getError();die();
        }
        $phpWord = new PhpWord();
        $section = $phpWord->addSection();
        $i = 0;
        $f = fopen($param['file'], 'r');
        while ( $i < $this->page ){
            $max = mt_rand($this->pmin, $this->pmax);
            for($j = 0; $j < $max; $j++){
                $row = fgets($f);
                $section->addText(htmlspecialchars($row) . "\r\n");
            }
            $diff = $this->pmax - $max;
            if( $diff ){
                for($k = 0; $k < $diff; $k++){
                    $section->addText(" \r\n");
                }
            }
            $loop = mt_rand(5, 10);
            for($a = 0; $a < $loop; $a++){
                fgets($f);
            }
            ++$i;
        }
        fclose($f);
        $objWriter = IOFactory::createWriter($phpWord, 'Word2007');
        $filename = './public/word/'.$param['name'].'软著.docx';
        $dir = dirname($filename);
        if( ! file_exists($dir) ){
            mkdir($dir, 0777, true);
        }
        $objWriter->save($filename);
    }
}
